#include <pic18fregs.h>
#include <pic16/pic18f96j60.h>
#include <string.h>
#include <stdlib.h>

#include "HardwareProfile.h"
#include "LCDBlocking.h"
#include "Compiler.h"
#include "GenericTypeDefs.h"

void init();

volatile unsigned long count = 0;
volatile unsigned long result = 0;

//This is the interrupt routine for timer0 interrupt.
void T0_ISR(void) __interrupt (2)
{
/*	if(PIR1bits.TMR1IF == 1)
	{
		PIR1bits.TMR1IF = 0;
		TMR1H |= 0x80;
		result = count * 256;
		count = 0;
	}
*/
	if(INTCONbits.T0IF == 1)
	{
		INTCONbits.T0IF = 0;
		count++;
	}
}

void RTC_ISR(void) __interrupt (1)
{
	if(PIR1bits.TMR1IF == 1)
	{
		PIR1bits.TMR1IF = 0;
		TMR1H |= 0x80;
		result = count * 256;
		count = 0;
	}

/*	if(INTCONbits.T0IF == 1)
	{
		INTCONbits.T0IF = 0;
		count++;
	}
*/}

void main()
{
	int i;

	init();

	//Preload for 1 second interrupt interval
	TMR1H = 0x80;
	TMR1L = 0x00;

	//Enable all interrupts
	INTCONbits.GIE = 1;
	RCONbits.IPEN = 1;

	i = 0;
	while(1)
	{
		i++;

		if(i >= 10000)
		{
			sprintf(LCDText, "fOSC:           %lu Hz", result);
			LCDUpdate();
			i = 0;
		}
	}
}

void init()
{	
	if(OSCCONbits.IDLEN)
		OSCCON = 0x82;
	else
		OSCCON = 0x02;
	
	OSCTUNE = 0x40;

	//Configure LED
	TRISJbits.TRISJ0 = 0;
	LATJbits.LATJ0 = 0;

	TRISGbits.TRISG5 = 0;

	//Initialize LCD
	LCDInit();

	//Configure Timer0
	T0CONbits.T08BIT = 1;
	T0CONbits.T0CS = 0;
	T0CONbits.PSA = 1;
	T0CONbits.TMR0ON = 1;

	//Configure interrupts
	INTCONbits.T0IE = 1;
	INTCON2bits.T0IP = 0;
	INTCONbits.T0IF = 0;

	//Preload for 1 second interrupt interval
	TMR1H = 0x80;
	TMR1L = 0x00;

	T1CONbits.RD16 = 0;
	T1CONbits.T1RUN = 0;
	T1CONbits.T1CKPS1 = 0;
	T1CONbits.T1CKPS0 = 0;
	T1CONbits.TMR1CS = 1;
	T1CONbits.T1OSCEN = 1;
	T1CONbits.T1SYNC = 1;

	T1CONbits.TMR1ON = 1;

	PIE1bits.TMR1IE = 1;
	IPR1bits.TMR1IP = 1;
	PIR1bits.TMR1IF = 0;

	INTCONbits.PEIE = 1;

	//Configure buttons
	BUTTON0_TRIS = 1;
	BUTTON1_TRIS = 1;
}
